import {defineStore} from 'pinia'
import {store} from '../index'

const menuStore = defineStore({
    id: 'menuList',
    state: () => ({
        menuList: [],
        opened: [],
        menuIdOfLastOpen: null,
    }),
    getters: {},
    actions: {
        setMenuList(menuList) {
            this.menuList = menuList;
        },
        setOpened(opened) {
            this.opened = opened;
            localStorage.setItem("menuStore.opened", JSON.stringify(opened));
        },
        openMenu(menu) {
            this.menuCodeOfLastOpen = menu.id;
            // 如果已经打开，则不再打开
            let index = this.opened.findIndex(item => item.id === menu.id);
            if (index !== -1) {
                // 将该菜单移动到最前面
                this.opened.splice(index, 1);
            }
            setTimeout(()=>{
                this.opened.unshift(menu);
                // 超过10个菜单时，删除最后一个
                if (this.opened.length > 10) {
                    this.opened.pop();
                }
                this.setOpened(this.opened);
            },100);
        },
        closeMenu(menu) {
            let index = this.opened.findIndex(item => item.id === menu.id);
            if (index !== -1) {
                this.opened.splice(index, 1);
                this.setOpened(this.opened);
            }
        },
    }
});

// 初始化opened
let initOpened = ()=> {
    let opened = localStorage.getItem("menuStore.opened");
    if (opened) {
        menuStore(store).setOpened(JSON.parse(opened));
    }
}

initOpened();

export {menuStore};

